<template>
    <div id="amapcontainer" style="width: 100%; height: 100%">
    </div>
</template>

<script>
import { pointlist } from './pointlist'
// import { mapState } from 'vuex'
export default {
    computed: {
        // ...mapState(['tabBarActive'])
    },
    data() {
        return {
            map: null,
            center:{
                lng: '', // 设置中心点
                lat: ''
            },
            signin: { // 设置默认打卡地点经纬度
                lng: '',
                lat: ''
            },
            radius:60,
            pointlist: pointlist,
            networkStatus:null,
            signInMarker:null
        }
    },
    activated() {
    },
    mounted() {
        
    },
    watch: {
        // '$route': {
        //     immediate: true,
        //     handler: function (to, from) {
        //         alert('路由变化了')
        //     }
        // }
    },
    methods: {
        test(){
            alert('11')
        },
        startLocation(){
            const that = this
            qing.call('startLocation', {
                interval: 5,
                success: function (result) {
                    const { data } = result
                    that.map.remove(that.signInMarker); // 清除原来的marker

                    that.signin.lng = data.longitude
                    that.signin.lat = data.latitude
                    that.signInMarker = new AMap.Marker({
                        position: new AMap.LngLat(that.signin.lng, that.signin.lat),
                        icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png',
                    })
                    that.map.add(that.signInMarker); // 签到位置

                    var infoWindow = new AMap.InfoWindow({
                        isCustom: true,  // 使用自定义窗体
                        content: '<div class="cus_info_window">当前位置1</div>', // 信息窗体的内容可以是任意 html 片段
                        offset: new AMap.Pixel(10, -30)
                    });
                    var onMarkerClick = function (e) {
                        infoWindow.open(map, e.target.getPosition()); // 打开信息窗体
                    }

                    that.signInMarker.on('click', onMarkerClick); // 绑定 click 事件
                }
            })
        },
        getStatus(){
            // qing.call('getNetworkType', {
            //     success: function (result) {
            //         alert('用户网络状态：' + JSON.stringify(result));
            //     }
            // });
            const that = this
            qing.on('networkAvailable', function (e) {
                alert('网络连接恢复11', JSON.stringify(e))
            })
            qing.on('networkDisAvailable', function (e) {
                alert('当前网络状态不佳，无法定位。可以使用拍照签到', JSON.stringify(e))
                alert('当前网络状态不佳，无法定位。可以使用拍照签到')
            })
        },
        // 设置中心点
        setCenterPoint(){
            this.pointlist.forEach(item=>{
                item.distance = Number(this.computedDistance([this.signin.lng, this.signin.lat], item.center))
            })
            const distanceArr = this.pointlist.map(a => a.distance)
            const min = distanceArr.reduce((minVal, currVal) => currVal < minVal ? currVal : minVal, distanceArr[0]);
            const minDistanceObj = this.pointlist.find(a => a.distance == min);
            if (minDistanceObj.center && minDistanceObj.center.length == 2) {
                this.center.lng = minDistanceObj.center[0]
                this.center.lat = minDistanceObj.center[1]
            }
        },
        // 获取当前位置并设置中心点
        getCurrentLocation(){
            const that = this
            qing.call('getLocation', {
                success: function (result) {
                    const { data } = result
                    that.signin.lng = data.longitude
                    that.signin.lat = data.latitude
                    that.setCenterPoint()
                    that.isInOrOutFlag();
                    that.initMap()
                }
            });
        },
        computedDistance(p1,p2){
            return AMap.GeometryUtil.distance(p1, p2);
        },
        isInOrOutFlag(){
            const dis = this.computedDistance([this.center.lng,this.center.lat],[this.signin.lng,this.signin.lat])
            if (dis > this.radius){ // 内勤1 外勤2
                // 外勤
                this.$store.commit('updateInOrOutFlag', 2)
            }else{
                this.$store.commit('updateInOrOutFlag', 1)
            }
        },
        // 获取签到点列表
        getSignInPointList(){

        },
        initSignInData() {
            // this.getSignInPointList();
            this.getCurrentLocation();
            this.startLocation();
        },
        initMap(){
            setTimeout(() => {
                let map = new AMap.Map('amapcontainer', {
                    zoom: 15,//级别
                    center: [this.center.lng, this.center.lat],//中心点坐标
                    viewMode: '3D', //使用3D视图
                    resizeEnable:true
                });
                this.map = map
                //比例尺 控件
                AMap.plugin('AMap.Scale', function () {
                    var scale = new AMap.Scale()
                    map.addControl(scale);
                });
                // 定位控件
                AMap.plugin('AMap.Geolocation', function () {
                    var geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true, // 是否使用高精度定位，默认：true
                        timeout: 10000, // 设置定位超时时间，默认：无穷大
                        // buttonOffset: [10, 20],  // 定位按钮的停靠位置的偏移量 默认
                        zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                        buttonPosition: 'RB' //  定位按钮的排放位置,  RB表示右下
                    })
                    map.addControl(geolocation);
                })


                var marker = new AMap.Marker({
                    position: [this.center.lng, this.center.lat],
                    title: "签到点",
                })
                this.signInMarker = new AMap.Marker({
                    position: new AMap.LngLat(this.signin.lng, this.signin.lat),
                    title: "我的位置",
                    icon: "//webapi.amap.com/theme/v1.3/markers/b/start.png", // 后续需要换
                })

                map.add(marker);// 打卡中心点添加到地图
                map.add(this.signInMarker); // 签到位置
                // 创建信息窗体
                var infoWindow = new AMap.InfoWindow({
                    isCustom: true,  // 使用自定义窗体
                    content: '<div class="cus_info_window">当前位置</div>', // 信息窗体的内容可以是任意 html 片段
                    offset: new AMap.Pixel(10, -30)
                });
                var onMarkerClick = function (e) {
                    infoWindow.open(map, e.target.getPosition()); // 打开信息窗体
                    // e.target 就是被点击的 Marker
                }

                this.signInMarker.on('click', onMarkerClick); // 绑定 click 事件

                
                // 签到区域
                for (let i = 0; i < this.pointlist.length; i += 1) {
                    let center = this.pointlist[i].center
                    let circleMarker = new AMap.CircleMarker({
                        center: center,
                        radius: this.radius,// 3D视图下，CircleMarker半径不要超过64px
                        strokeColor: 'white',
                        strokeWeight: 2,
                        strokeOpacity: 0.5,
                        fillColor: '#b3d8ff',
                        fillOpacity: 0.5,
                        zIndex: 10,
                        bubble: true,
                        cursor: 'pointer',
                        clickable: true
                    })
                    circleMarker.setMap(map)
                }
            }, 800);
        },
    },
    mounted() {
        //DOM初始化完成进行地图初始化
        this.initSignInData()
    }
}
</script>

<style lang="scss">
.cus_info_window {
    padding: 10px;
    background-color: #fff;
}
</style>
